package com.lazason.wib4android;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import weibo4andriod.Paging;
import weibo4andriod.RetweetDetails;
import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import weibo4andriod.http.AccessToken;
import weibo4andriod.http.RequestToken;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.lazason.wib4android.AsyncImageLoader.ImageCallback;

public class Wib extends BasicActivity {
	Weibo weibo;
	static final String WIB = "com.lazason.wib";
	ListView listView;
	MyAdapter adapter;
	private ProgressBar progressBar;
	LinearLayout layout;
	int page = 1;
	boolean isLoading = false;
	TimeLineTask timeLineTask;
	Paging paging;
	boolean firstLoadImage = true;
	AsyncImageLoader asyncImageLoader;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.timeline);
		listView = (ListView) findViewById(android.R.id.list);
		paging = new Paging();
		paging.setPage(page);
		Uri uri = this.getIntent().getData();
		int mode = Activity.MODE_PRIVATE;
		asyncImageLoader = new AsyncImageLoader();
		SharedPreferences mySharedPreferences = getSharedPreferences(WIB, mode);
		String token = mySharedPreferences.getString("token", null);
		String tokenSecret = mySharedPreferences.getString("tokenSecret", null);

		// List<weibo4andriod.Status> friendsTimeline = null;
		if (token != null && tokenSecret != null) {
			weibo = OAuthConstant.getInstance().getWeibo();
			weibo.setToken(token, tokenSecret);
			adapter = new MyAdapter(this, MyApplication.data,
					R.layout.listitem, new String[] { "profile", "weibo",
							"username","picture","retweetedText","retweetedThumbnailPic" }, new int[] { R.id.profile, R.id.weibo,
							R.id.username ,R.id.picture,R.id.retweetedText,R.id.retweetedThumbnailPic},listView);
			listView.setAdapter(adapter);
		} else {
			try {
				RequestToken requestToken = OAuthConstant.getInstance()
						.getRequestToken();
				AccessToken accessToken = requestToken.getAccessToken(uri
						.getQueryParameter("oauth_verifier"));
				OAuthConstant.getInstance().setAccessToken(accessToken);
				weibo = OAuthConstant.getInstance().getWeibo();
				weibo.setToken(OAuthConstant.getInstance().getToken(),
						OAuthConstant.getInstance().getTokenSecret());

				SharedPreferences.Editor editor = mySharedPreferences.edit();
				editor.putString("token", accessToken.getToken());
				editor.putString("tokenSecret", accessToken.getTokenSecret());
				editor.commit();
				layout = new LinearLayout(this);
				progressBar = new ProgressBar(this);
				// 进度条显示位置
				progressBar.setPadding(0, 0, 15, 0);
				// 把进度条加入到layout中
				layout.addView(progressBar);

				// setContentView(layout);

				// 文本内容
				TextView textView = new TextView(this);
				textView.setText("加载中...");
				textView.setGravity(Gravity.CENTER_VERTICAL);
				layout.addView(textView);
				listView.addHeaderView(layout);
				FirstTimeLineTask ftlt = new FirstTimeLineTask();
				ftlt.execute();
			} catch (WeiboException e) {
				e.printStackTrace();
			}
		}
		listView.setOnScrollListener(new OnScrollListener() {
			 

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub

				if (totalItemCount != 0) {
					if (firstVisibleItem + visibleItemCount > (totalItemCount - 20)
							&& page < 1000) {

						if (!isLoading) {

							isLoading = true;
							// 开线程去下载网络数据

							timeLineTask = new TimeLineTask();
							page++;
							timeLineTask.execute(page);
						}

					}

				}
				
			}

			@Override
			public void onScrollStateChanged(AbsListView paramAbsListView,
					int paramInt) {
				// TODO Auto-generated method stub
				
			}

		});
		registerForContextMenu(listView);
	}
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
	    ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);  
        menu.setHeaderTitle("Context Menu");  
        menu.add(0, 0, 0, "Forward");  
        menu.add(0, 1, 1, "Comments");  
	}	
	@Override
	public boolean onContextItemSelected(MenuItem aItem) {
	AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) aItem.getMenuInfo();

	/* Switch on the ID of the item, to get what the user selected. */
	switch (aItem.getItemId()) {
	case 0:
	/* Get the selected item out of the Adapter by its position. */
	Map info =  (Map) listView.getAdapter().getItem(menuInfo.position);
	Log.d("Wib", " position "+menuInfo.position);
	Log.d("Wib", " screen_name "+info.get("username"));
	Log.d("Wib", " user id "+info.get("id"));
	/* Remove it from the list.*/
	//fakeFavs.remove(favContexted);

	//refreshFavListItems();
	return true; /* true means: “we handled the event”. */
	}
	return false;
	}
	private class FirstTimeLineTask extends
			AsyncTask<Void, Void, List<weibo4andriod.Status>> {

		protected List<weibo4andriod.Status> doInBackground(Void... arg) {
			List<weibo4andriod.Status> friendsTimeline = null;
            
			try {

				friendsTimeline = weibo.getFriendsTimeline();

			} catch (WeiboException we) {
				we.printStackTrace();

			} catch (Exception e) {
				e.printStackTrace();

			}

			return friendsTimeline;
		}

		protected void onPostExecute(List<weibo4andriod.Status> friendsTimeline) {
			MyApplication.data = new ArrayList<Map<String, Object>>();
			for (weibo4andriod.Status status : friendsTimeline) {
				Log.d("WIB", status.toString());
				Map<String, Object> map = Util.status2Map(status);
//				Map<String, Object> map = new HashMap<String, Object>();
//
//				map.put("profile", status.getUser().getProfileImageURL()
//						.toString());
//				map.put("weibo", status.getText());
//				map.put("username", status.getUser().getName());
//				map.put("id", status.getUser().getId());
				MyApplication.data.add(map);

			}
			
			adapter = new MyAdapter(Wib.this, MyApplication.data,
					R.layout.listitem, new String[] { "profile", "weibo",
							"username","picture","retweetedText","retweetedThumbnailPic" }, new int[] { R.id.profile, R.id.weibo,
							R.id.username ,R.id.picture,R.id.retweetedText,R.id.retweetedThumbnailPic},listView);

			listView.setAdapter(adapter);
			listView.removeHeaderView(layout);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			// listView.addFooterView(layout);
		}

	}

	private class TimeLineTask extends
			AsyncTask<Integer, Void, List<weibo4andriod.Status>> {

		protected List<weibo4andriod.Status> doInBackground(Integer... page) {
			List<weibo4andriod.Status> friendsTimeline = null;
			friendsTimeline = null;
			try {

				System.out.println("page : " + page[0].intValue());
				paging.setPage(page[0]);

				friendsTimeline = weibo.getFriendsTimeline(paging);

			} catch (WeiboException we) {
				we.printStackTrace();

			} catch (Exception e) {
				e.printStackTrace();

			}
			

			return friendsTimeline;
		}

		protected void onPostExecute(List<weibo4andriod.Status> friendsTimeline) {
			if (friendsTimeline == null) {
				Toast.makeText(getApplicationContext(), "没有更多的微博",
					     Toast.LENGTH_SHORT).show();
				isLoading = false;
				return;
			}
            boolean isWifi = MyApplication.isWifi(Wib.this);
			for (weibo4andriod.Status status : friendsTimeline) {
				Map<String, Object> map = Util.status2Map(status);

				
				MyApplication.data.add(map);
				
			}

			// listView.removeFooterView(layout);

			adapter.notifyDataSetChanged();
			isLoading = false;

		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			// listView.addFooterView(layout);
		}

	}
	void preLoadOriginalImage(String id, String url){
		asyncImageLoader
		.loadDrawable(this, url, id,
				Thread.NORM_PRIORITY,
				new ImageCallback() {
					public void imageLoaded(
							Drawable imageDrawable,
							String imageUrl,
							String id) {
						
					}
				});
	}
}
